// 导入默认菜单配置
import DEFAULT_MENU from './config.js';

// 在文件开头添加一个变量来控制动画状态
let isRolling = false;

function showResult(food) {
  const resultElement = document.querySelector('.food-result');
  const pickButton = document.getElementById('pickButton');
  
  // 如果正在滚动，则停止并显示结果
  if (isRolling) {
    isRolling = false;
    clearInterval(window.rollInterval);
    resultElement.classList.remove('rolling'); // 移除抖动动画
    resultElement.style.opacity = '1';
    resultElement.textContent = food;
    pickButton.textContent = '换一个';
    return;
  }
  
  // 开始滚动动画
  isRolling = true;
  pickButton.textContent = '就它了';
  resultElement.classList.add('rolling');
  
  // 创建持续滚动动画，直到用户点击"就它了"
  window.rollInterval = setInterval(() => {
    // 随机从菜单中选择一个显示
    const randomFood = customMenu[Math.floor(Math.random() * customMenu.length)];
    resultElement.textContent = randomFood;
  }, 100); // 每100ms更新一次
}

// 添加重置函数
function resetPickButton() {
  const resultElement = document.querySelector('.food-result');
  const pickButton = document.getElementById('pickButton');
  
  if (resultElement.textContent === '点击下方按钮获取美食灵感') {
    pickButton.textContent = '随机选择';
  }
}

let customMenu = JSON.parse(localStorage.getItem('customMenu'));
if (!customMenu) {
  // 如果本地存储中没有数据，使用默认菜单初始化
  customMenu = [...DEFAULT_MENU.dishes];
  saveDishes(); // 保存到本地存储
}

function openMenuModal() {
  document.getElementById('menuModal').style.display = 'block';
  renderDishList();
}

function closeMenuModal() {
  document.getElementById('menuModal').style.display = 'none';
}

function addDish() {
  const input = document.getElementById('newDish');
  const dish = input.value.trim();
  
  if (dish) {
    if (!customMenu.includes(dish)) { // 避免重复添加
      customMenu.unshift(dish); // 使用 unshift 将新菜品添加到数组开头
      saveDishes();
      renderDishList();
      input.value = '';
    } else {
      alert('这个菜品已经在菜单中了哦！');
    }
  }
}

function deleteDish(index) {
  customMenu.splice(index, 1);
  saveDishes();
  renderDishList();
}

function renderDishList() {
  const dishList = document.getElementById('dishList');
  
  if (customMenu.length === 0) {
    dishList.innerHTML = '<div class="empty-message">菜单是空的，快来添加几个菜品吧！</div>';
    return;
  }

  dishList.innerHTML = customMenu.map((dish, index) => `
    <div class="dish-item">
      <span>${dish}</span>
      <button class="delete-btn" data-index="${index}">删除</button>
    </div>
  `).join('');

  // 为所有删除按钮添加事件监听
  document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      deleteDish(parseInt(btn.dataset.index));
    });
  });
}

function saveDishes() {
  localStorage.setItem('customMenu', JSON.stringify(customMenu));
}

function pickFood() {
  const menu = customMenu.length > 0 ? customMenu : DEFAULT_MENU.dishes;
  const randomIndex = Math.floor(Math.random() * menu.length);
  const selectedFood = menu[randomIndex];
  showResult(selectedFood);
}

function clearMenu() {
  // 创建确认对话框
  const dialog = document.createElement('div');
  dialog.className = 'confirm-dialog';
  dialog.innerHTML = `
    <p>确定要清空所有菜单吗？此操作不可恢复。</p>
    <div class="button-group">
      <button class="button button-danger button-small" id="confirmClear">确定</button>
      <button class="button button-secondary button-small" id="cancelClear">取消</button>
    </div>
  `;
  document.body.appendChild(dialog);

  // 添加确认和取消事件
  document.getElementById('confirmClear').addEventListener('click', () => {
    customMenu = [];
    saveDishes();
    renderDishList();
    document.body.removeChild(dialog);
  });

  document.getElementById('cancelClear').addEventListener('click', () => {
    document.body.removeChild(dialog);
  });
}

function importMenu(file) {
  const reader = new FileReader();
  reader.onload = (event) => {
    const content = event.target.result;
    const dishes = content.split('\n')
      .map(line => line.trim())
      .filter(line => line.length > 0); // 过滤空行

    // 检查是否有新菜品要导入
    const newDishes = dishes.filter(dish => !customMenu.includes(dish));
    
    if (newDishes.length > 0) {
      customMenu.push(...newDishes);
      saveDishes();
      renderDishList();
      alert(`成功导入 ${newDishes.length} 个新菜品！`);
    } else {
      alert('没有新的菜品需要导入！');
    }
  };
  reader.readAsText(file);
}

function restoreDefaultMenu() {
  // 创建确认对话框
  const dialog = document.createElement('div');
  dialog.className = 'confirm-dialog';
  dialog.innerHTML = `
    <p>确定要恢复默认菜单吗？当前菜单将被覆盖。</p>
    <div class="button-group">
      <button class="button button-secondary button-small" id="confirmRestore">确定</button>
      <button class="button button-secondary button-small" id="cancelRestore">取消</button>
    </div>
  `;
  document.body.appendChild(dialog);

  // 添加确认和取消事件
  document.getElementById('confirmRestore').addEventListener('click', () => {
    customMenu = [...DEFAULT_MENU.dishes]; // 创建新数组，避免引用
    saveDishes();
    renderDishList();
    document.body.removeChild(dialog);
  });

  document.getElementById('cancelRestore').addEventListener('click', () => {
    document.body.removeChild(dialog);
  });
}

function exportMenu() {
  // 创建要导出的内容
  const content = customMenu.join('\n');
  
  // 创建 Blob 对象
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
  
  // 创建下载链接
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = '我的美食菜单.txt';
  
  // 添加到文档并触发点击
  document.body.appendChild(a);
  a.click();
  
  // 清理
  document.body.removeChild(a);
  URL.revokeObjectURL(a.href);
}

// 添加事件监听器
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('pickButton').addEventListener('click', pickFood);
  document.getElementById('menuButton').addEventListener('click', openMenuModal);
  document.getElementById('addButton').addEventListener('click', addDish);
  document.getElementById('closeButton').addEventListener('click', closeMenuModal);
  
  // 点击模态框外部关闭
  document.getElementById('menuModal').addEventListener('click', (event) => {
    if (event.target === event.currentTarget) {
      closeMenuModal();
    }
  });

  // 为新菜品输入框添加回车键监听
  document.getElementById('newDish').addEventListener('keypress', (event) => {
    if (event.key === 'Enter') {
      addDish();
    }
  });

  // 页面加载时检查并重置按钮文字
  resetPickButton();

  // 清空菜单按钮
  document.getElementById('clearButton').addEventListener('click', clearMenu);

  // 导入菜单按钮
  document.getElementById('importButton').addEventListener('click', () => {
    document.getElementById('menuFile').click();
  });

  // 文件选择改变事件
  document.getElementById('menuFile').addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      if (file.type === 'text/plain') {
        importMenu(file);
      } else {
        alert('请选择 .txt 格式的文件！');
      }
      event.target.value = ''; // 重置文件输入
    }
  });

  // 恢复默认菜单按钮
  document.getElementById('defaultButton').addEventListener('click', restoreDefaultMenu);

  // 导出菜单按钮
  document.getElementById('exportButton').addEventListener('click', exportMenu);
}); 